<?php

// +----------------------------------------------------------------------
// 内部请示
// +----------------------------------------------------------------------

namespace app\document\controller;
error_reporting(0);
use app\document\service\DataService;
use library\Controller;
use think\Db;


/**
 * 内部请示
 */
class Docin extends Controller
{

    /**
     * 绑定当前数据表
     * @var string
     */
    protected $table = 'Docout';

    /**
     * 请示列表
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {

    	$allusers = session('admin_user')['nickname'];
        $this->title = '请示列表';
        $this->_query($this->table)->like('title')
        	 ->where("allusers LIKE '%".$allusers."%' AND is_deleted=0  AND wenhao=5")
        	 ->equal('status')->order(' status ASC , id DESC')->page();
    }

    /**
     * 已办结
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function doc_done()
    {

    	$allusers = session('admin_user')['nickname'];
        $this->title = '已完成';
        $this->_query($this->table)->like('title')
        	 ->where("allusers LIKE '%".$allusers."%' AND is_deleted=0 AND status=2 AND wenhao=5 ")
        	 ->equal('status')->order(' status ASC , id DESC')->page();
        $this->fetch();
    }

    protected function _page_filter(&$data){
        foreach ($data as &$vo) {
            $rs = Db::name('Docoutflow')->field('*')->where(" username ='".session('admin_user.nickname')."' AND docid= '".$vo['id']."'  AND status =1 AND doctypes= 'docout' AND info='' ")->find();
            if($rs){

                $count =Db::name('Docoutflow')->where("docid= '".$vo['id']."'  AND status =1 AND doctypes= 'docout' AND info='' AND flag< ".$rs['flag'])->count('id');
                if($count >=1){
                     $vo['flowcount'] = 0;
                }else{
                     $vo['flowcount'] = 1;
                }               
            }else{
                $vo['flowcount'] = 0;
            }
            
        }
        #print_r($rs);
    }


    /**
     * 添加
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {
    	$this->title = '发文登记';

    	
    	if ($this->request->isPost()) {

    		list($data1, $string) = [$this->request->post(), []];

            $data1['addtime'] =time();

            if($data1['docauthor'] ==''){
                $data1['docauthor'] =session('admin_user')['nickname'];
            }
            

    		$data1['allusers'] = $data1['docauthor'].','.$data1['keshifuzeren'].','.$data1['shouwenwenyuan'].','.$data1['fenguanlingdao'].','.session('admin_user')['nickname'];

            $data1['wenhao'] =5;

    		$ids =Db::name('Docout')->strict(false)->insertGetId($data1);
    		
    		//拟稿人发布
	    	if($data1['docauthor'] !=''){
	    		$this->Insertflow($data1['docauthor'] , $info ='拟稿完成' , $types='nigao' , $ids  , $flag = 0 , 'docin');
	    	}

    		//科室负责人
	    	$this->Insertflow($data1['keshifuzeren'] , $info ='' , $types='keshifuzeren' , $ids , $flag = 1 , 'docin');

    		//收发文员/拟稿人复核
	    	$this->Insertflow($data1['shouwenwenyuan'] , $info ='' , $types='shouwenwenyuan' , $ids , $flag = 2 , 'docin');

    		//办公室主任
	    	//$this->Insertflow($data1['bangongshizhuren'] , $info ='' , $types='bangongshizhuren' , $ids , $flag = 3 , 'docin');

    		//分管领导
	    	$this->Insertflow($data1['fenguanlingdao'] , $info ='' , $types='fenguanlingdao' , $ids , $flag = 4 , 'docin');

    		//主要领导
    		//$this->Insertflow($data1['zhuyaolingdao'] , $info ='' , $types='zhuyaolingdao' , $ids , $flag = 5 , 'docin');

    		//插入附件
        	list($post, $datas) = [$this->request->post(), []];
        	if (isset($post['fileurl']) && is_array($post['fileurl'])) {
        		$files =[];
                foreach (array_keys($post['fileurl']) as $key) {
                	array_push($files, [
	                    'docid'     => $ids,
	                    'username'    => $post['docauthor'],
	                    'original_name' => $post['original_name'][$key],
	                    'fileext'   => $post['fileext'][$key],
	                    'filesize'  => $post['filesize'][$key],
	                    'fileurl'   => $post['fileurl'][$key],
	                    'filename'  => $post['filename'][$key],
	                    'md5code'   => $post['md5code'][$key],
	                    'sha1code'  => $post['sha1code'][$key],
	                    'flag'		=> 'docin',
                	]);
                }
                if (!empty($files)) {
                    Db::name('Attachment')->insertAll($files);
                }
        	}

        	$this->success('恭喜, 数据保存成功!', '/admin.html#/document/docin/index.html');
    	
    	}


    	//增加发文的表单如下-----------------------------------
    	$list = Db::name('SystemUser')->field('id,username,nickname')->where('id >10000')->where(['status'=>'1'])->select();
    	$str ='';
    	foreach ($list as &$value) {
    		$str .="{name:'".$value['nickname']."', value: '".$value['nickname']."'},\r\n";
    	}

    	$shouwenwenyuan ="";
    	$keshifuzeren ='';
    	$fenguanlingdao ="";
    	$files =[];
    	$docauthor =session('admin_user.nickname');
    	$this->assign('files' , $files);
    	$this->assign('docauthor' , $docauthor);  	//拟稿人、发送人
    	$this->assign('keshifuzeren' , $keshifuzeren);  	
    	$this->assign('shouwenwenyuan' , $shouwenwenyuan);  	
    	$this->assign('fenguanlingdao' , $fenguanlingdao);  		
    	$this->assign('str' , $str);  	
        $this->_form($this->table, 'form');
    }



    //新增的时候插入流程
    private function Insertflow($data , $info , $types ,$ids , $flag ,$doctypes)
    {
    	if($data ==''){
    		return false;
    	}
		$tmp1 = explode(',' , $data);
		$flow1 =[];
		if(is_array($tmp1)){
			foreach ($tmp1 as &$v) {
				if($v !=''){
					array_push($flow1, [
	                    'docid'     => $ids,
	                    'username'  => $v,
	                    'types'     => $types,
	                    'info'      => $info,
	                    'addtime'   => time(),
	                    'files'     => '',
	                    'flag'		=> $flag,
	                    'doctypes'	=> $doctypes,
                	]);
				}
			}
		}else{
			$flow1[] =[
                'docid'     => $ids,
                'username'  => $tmp1,
                'types'     => $types,
                'info'      => $info,
                'addtime'   => time(),
                'files'     => '',
                'flag'		=> $flag,
                'doctypes'	=> $doctypes,
            ];
		}
        if (!empty($flow1)) {
            Db::name('Docoutflow')->insertAll($flow1);
        }
        return true;
    }


    /**
     * 修改
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {
        $this->title = '查看文件';

    	$id =intval($this->request->param('id'));

    	$rs =Db::table('Docout')->where('id',$id)->find();

        if (stripos($rs['allusers'], session('admin_user')['nickname'] ) ===FALSE) {
            $this->error('权限不足，操作失败！' );
        }

    	$my_flow = Db::table('Docoutflow')
    			->where( "  username ='".session('admin_user.nickname')."' AND docid='".$rs['id']."' AND status=1 AND info ='' ")
    			->find();

    	if($my_flow['flag'] !='' ){
    		$my_flow_count = Db::table('Docoutflow')
    			->where( "  docid='".$rs['id']."' AND status=1 AND info ='' AND flag <".$my_flow[flag]." ")
    			->count('id');
    	}else{
    		$my_flow_count ='';
    	}

    	$rs_flow = Db::table('Docoutflow')
    			->where( "  username ='".session('admin_user.nickname')."' AND docid='".$rs['id']."' AND status=1 AND info ='' ")
    			->count('id');

    	$list_flow = Db::table('Docoutflow')
    			->where( "  docid='".$rs['id']."' AND status=1 AND info !='' ")
    			->order('addtime ASC,id ASC')
    			->select();

    	if ($this->request->isPost()) {

    		if($rs['status'] ==2)
    		{
    			$this->error('该文件已经办结，无法再流转！' );
    		}


    		list($data1, $string) = [$this->request->post(), []];
	    	if (session('admin_user')['nickname'] !== $data1['docauthor'] ) {
	    		$this->error('权限不足，操作失败' );
	    	}
	    	
    		$data1['allusers'] = $data1['docauthor'].','.$data1['keshifuzeren'].','.$data1['shouwenwenyuan'].','.$data1['bangongshizhuren'].','.$data1['fenguanlingdao'].','.$data1['zhuyaolingdao'].','.session('admin_user')['nickname'];
    		$data1['allusers'] =join(',' , array_unique(  explode(',' ,$data1['allusers']) ) ) ;

    		//领导批示
    		$data1['keshifuzeren'] = $this->saveEdit($data1['keshifuzeren'] , $rs['keshifuzeren'] , $types='keshifuzeren' , $rs['id'] , 1, 'docin');
    		$data1['shouwenwenyuan'] = $this->saveEdit($data1['shouwenwenyuan'] , $rs['shouwenwenyuan']  , $types='shouwenwenyuan' , $rs['id'] , 2, 'docin');

    		$data1['fenguanlingdao'] = $this->saveEdit($data1['fenguanlingdao'] , $rs['fenguanlingdao'] , $types='fenguanlingdao' , $rs['id'] ,4, 'docin');


			Db::name('Docout')
			    ->where('id', $data1['id'])
			    ->strict(false)
			    ->data($data1)
			    ->update();


        	list($post, $datas) = [$this->request->post(), []];
        	if (isset($post['fileurl']) && is_array($post['fileurl'])) {
        		$files =[];
                foreach (array_keys($post['fileurl']) as $key) {
                	array_push($files, [
	                    'docid'     => $data1['id'],
	                    'username'    => $post['docauthor'],
	                    'original_name' => $post['original_name'][$key],
	                    'fileext'   => $post['fileext'][$key],
	                    'filesize'  => $post['filesize'][$key],
	                    'fileurl'   => $post['fileurl'][$key],
	                    'filename'  => $post['filename'][$key],
	                    'md5code'   => $post['md5code'][$key],
	                    'sha1code'  => $post['sha1code'][$key],
	                    'flag'		=> 'docin',
                	]);
                }
                if (!empty($files)) {
                    Db::name('Attachment')->insertAll($files);
                }
        	}

        	$this->success('恭喜, 数据保存成功!', '/admin.html#/document/docin/index.html');
    	}


    	$files =Db::table('Attachment')->where(['docid'=>$id, 'flag'=>'docin'])->select();

    	$keshifuzeren =$this->showUser($rs['keshifuzeren']);

    	$shouwenwenyuan =$this->showUser($rs['shouwenwenyuan']);

    	$fenguanlingdao =$this->showUser($rs['fenguanlingdao']);

    	$list = Db::name('SystemUser')->field('id,username,nickname')->where('id >10000')->where(['status'=>'1'])->select();
    	$str ='';
    	foreach ($list as &$value) {
    		$str .="{name:'".$value['nickname']."', value: '".$value['nickname']."'},\r\n";
    	}

    	$this->assign('rs_flow' , $rs_flow);
    	$this->assign('my_flow_count' , $my_flow_count);
    	$this->assign('id' , $id);
    	$this->assign('files' , $files);
    	$this->assign('str' , $str);
    	$this->assign('keshifuzeren' , $keshifuzeren);
    	$this->assign('shouwenwenyuan' , $shouwenwenyuan);
    	$this->assign('fenguanlingdao' , $fenguanlingdao);
    	$this->assign('docauthor' , $rs['docauthor']);
    	$this->assign('remark' , $rs['remark']);
    	$this->assign('list_flow' , $list_flow);
        $this->_form($this->table, 'form');
    }


    private function showUser($data)
    {
    	if($data !=''){
    		$tmp1 = explode(',' , $data);
    		$str1 ='';
    		if(is_array($tmp1)){
    			foreach ($tmp1 as $key => &$v) {
    				$str1 .="'".$v."',";
    			}

    		}else{
    			$str1 =$data;
    		}
    		$str1 =rtrim($str1 , ',');
    	}
    	return $str1;
    }


    private function saveEdit($data1 , $data2 , $types , $ids , $flag , $doctypes)
    {
    		$data1_tmp =$data1; //表单提交的数据
    		if($data1_tmp ==''){
    			return false;
    		}
    		$array1 =explode(',' ,$data1_tmp);

    		if($data2 !='' ){
	    		$this->delflow($data2 , $types , $ids);  //软删除
    		}

    		$tmp_leader =join(',' , array_unique(  $array1 ) ) ; //去重重组

    		$tmp1 = explode(',' , $tmp_leader);
    		$flow1 =[];
    		if( count($tmp1) >= 1 ){
    			foreach ($tmp1 as &$v) {
    				$tmp_count = Db::table('Docoutflow')->where( ['username' => $v , 'types'=>$types ,'docid'=>$ids ])->count('id');
    				if($tmp_count ==1){
    					Db::table('Docoutflow')->where("  username ='".$v."' AND types='".$types."' AND docid= '".$ids."'  ")->update(['status'=>'1']);
    				}
    				if($v !='' && $tmp_count ==0 ){
						array_push($flow1, [
		                    'docid'     => $ids,
		                    'username'  => $v,
		                    'types'     => $types,
		                    'info'      => '',
		                    'addtime'   => time(),
		                    'files'     => '',
		                    'flag'		=> $flag,
		                    'doctypes'	=> $doctypes,
	                	]);
    				}
    			}
    		}
            if (!empty($flow1)) {
                Db::name('Docoutflow')->insertAll($flow1);
            }
    		return $data1_tmp;
    }


    /**
     * 软删除
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function delflow($data , $flag , $docid )
    {
    	$tmp1 = explode(',' , $data);
    	if(is_array($tmp1)){
    		foreach ($tmp1 as $key => $v) {
    			Db::table('Docoutflow')->where("  username ='".$v."' AND types='".$flag."' AND docid='".$docid."' ")->update(['status'=>'0']);
    		}
    	}else{
    		Db::table('Docoutflow')->where(" username ='".$tmp1."' AND types='".$flag."' AND docid='".$docid."' ")->delete(['status'=>'0']);
    	}
    }



    /**
     * 更改状态
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function state()
    {
    	$id =intval($this->request->param('id'));

    	$rs =Db::table('Document')->where(['id'=>$id])->find();

    	if($rs['docauthor'] !=session('admin_user')['nickname']){
    		$this->error('此文件无法强制办结!');
    	}

        $this->_save($this->table, ['status' => input('status', '2')]);
    }

    /**
     * 强制办结
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        $this->_delete($this->table);
    }

    /**
     * 文档打印
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function printdoc()
    {
    	$id =intval($this->request->param('id'));

    	$rs =Db::table('Docout')->where(['id'=>$id , 'status'=>2])->find();

    	if(!$rs)
    	{
    		$this->error('文档不存在!');
    	}

        if (stripos($rs['allusers'], session('admin_user')['nickname'] ) ===FALSE) {
            $this->error('权限不足，操作失败！' );
        }

    	$file_list =Db::table('Attachment')
    			->where( "  docid='".$rs['id']."' AND flag='docout' ")
    			->select();
    	$flow_list = Db::table('Docoutflow')
    			->where( "  docid='".$rs['id']."' AND doctypes='docout' AND status=1 AND info<>'' ")
    			->select();

    	$this->assign('rs' , $rs);
    	$this->assign('file_list' , $file_list);
    	$this->assign('flow_list' , $flow_list);


    	$this->fetch();
    }

    /**
     * 批示文件
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function saveinfo()
    {
    	if ($this->request->isPost()) {
    		$data =$this->request->param();
    		$rs['info'] = $data['info'];
    		$rs['docid'] = $data['docid'];
    		$rs['username'] = session('admin_user.nickname');
    		$rs['status'] =1;

    		Db::table('Docoutflow')->where("  username ='".$rs['username']."' AND doctypes='docin'  AND docid='".$rs['docid']."' AND status=1 AND info ='' ")
    		->update(['info'=>$rs['info'], 'addtime'=>time() ]);

    		$rs_flow = Db::table('Docoutflow')
    			->where( "  docid='".$rs['docid']."' AND status=1 AND info ='' AND doctypes='docin' ")
    			->count('id');

            
    		if($rs_flow ==0){
    			Db::table('Docout')->where("  id='".$rs['docid']."'  ")
    				->update( ['status'=>2 ]);
    		}


    		$res =[];
    		$res['code']  ='1';
    		$res['status']  ='success';
    		$res['msg']  ='保存成功！';
    		return $res;
    	}
    }



    public function upload()
    {
        if($this->request->file('file')){
            $file       = $this->uploadfile('file','' ,[] , session('admin_user')['id']);
            if ($file) {
                echo json_encode($file);
            } else {
                echo json_encode($file);
            }
        }
    }


    public function uploadfile($name, $path = '', $validate = [], $user_id = 0)
    {
        $config = config('attchment');
        $file   = request()->file($name);
        if ($file) {
            $file_path = $config['path'] . $path;
            $file_url  = $config['url'] . $path;
            $validate  = array_merge($config['validate'], $validate);
            $info      = $file->validate($validate)->move($file_path);
            if ($info) {
                $file_info = [
                	'code'          => 0 ,
                    'user_id'       => $user_id,
                    'original_name' => $info->getInfo('name'),
                    'save_name'     => $info->getFilename(),
                    'save_path'     => str_replace("\\", "/",$file_path . $info->getSaveName()),
                    'extension'     => $info->getExtension(),
                    'mime'          => $info->getInfo('type'),
                    'size'          => $info->getSize(),
                    'md5'           => $info->hash('md5'),
                    'sha1'          => $info->hash(),
                    'url'           => str_replace("\\", "/",$file_url . $info->getSaveName())
                ];
                return $file_info;
            } else {
                return $file->getError();
            }
        } else {
            return '无法获取文件';
        }
        return false;
    }


}
